"""
用户管理
"""
from django.shortcuts import render, redirect, HttpResponse, reverse
from rbac import models


# from rbac.forms.UserForms import UserForm

def user_list(request):
    user_queryset = models.UserInfo.objects.all()
    return render(request, 'rbac/user_list.html', {'users': user_queryset})


def user_add(request):
    user_l = [item['name'] for item in models.UserInfo.objects.all().values('name')]
    status = {}
    if request.method == 'POST':
        username = request.POST.get('name', '')
        password = request.POST.get('pwd', '')
        re_password = request.POST.get('re_pwd', '')
        email = request.POST.get('email', '')
        if username in user_l:
            status['user_msg'] = '该用户已存在'
        elif password != re_password:
            status['pwd_msg'] = '两次密码不一致'
        else:
            models.UserInfo.objects.create(name=username, password=password, email=email)
            return redirect(reverse('rbac:user_list'))
    return render(request, 'rbac/user_add.html', locals())


def user_edit(request, user_id):
    user_l = [item['name'] for item in models.UserInfo.objects.all().values('name')]
    user_obj = models.UserInfo.objects.filter(pk=user_id).first()
    status = {}
    if request.method == 'POST':
        new_username = request.POST.get('name')
        new_email = request.POST.get('email')
        if new_username in user_l:
            status['msg'] = '用户名已存在'
            return render(request, 'rbac/user_edit.html', locals())
        models.UserInfo.objects.filter(pk=user_id).update(name=new_username, email=new_email)
        return redirect(reverse('rbac:user_list'))
    return render(request, 'rbac/user_edit.html', locals())


def user_del(request,user_id):
    """
    删除用户
    :param request:
    :param user_id:
    :return:
    """
    cancel_url = '/rbac/user/list/'
    if request.method == 'POST':
        models.UserInfo.objects.filter(pk=user_id).delete()
        return redirect(reverse(('rbac:user_list')))
    return  render(request, 'rbac/del.html', {'cancel':cancel_url})

def user_set_pwd(request,user_id):
    org_pwd = models.UserInfo.objects.filter(pk=user_id).first()
    status={}
    if request.method == 'POST':
        old_pwd = request.POST.get('old_pwd')
        pwd = request.POST.get('pwd')
        re_pwd = request.POST.get('re_pwd')
        if old_pwd != org_pwd.password:
            status['error']= '旧密码错误'
            return render(request, 'rbac/user_set_pwd.html',locals())
        elif pwd != re_pwd:
            status['msg'] = '两次密码输入不一致'
            return render(request, 'rbac/user_set_pwd.html',locals())
        models.UserInfo.objects.filter(pk=user_id).update(password=pwd)
        return redirect(reverse('rbac:user_list'))
    return render(request,'rbac/user_set_pwd.html')